package com.xxkj.drugtraceability.ui.prescriptiondrugcollection

import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityPrescriptiondrugcollectionBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupCollectTopViewBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupTopViewBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/10 14:43
 * description:处方发药采集
 */
class PrescriptionDrugCollectionActivity:BaseVMActivity() {
    private val binding by binding<ActivityPrescriptiondrugcollectionBinding>(R.layout.activity_prescriptiondrugcollection)
    private val viewModel by viewModel<PrescriptionDrugCollectionViewModel>()
    private lateinit var adapter: PrescriptionDrugCollectionAdapter
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@PrescriptionDrugCollectionActivity)
            adapter = PrescriptionDrugCollectionAdapter{
                viewModel.barcode = ""
                viewModel.lastIndex = viewModel.selectIndex.value?:-1
                viewModel.selectIndex.postValue(it)
            }
            tvCancel.clickN {
                YellowDialog(this@PrescriptionDrugCollectionActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@PrescriptionDrugCollectionActivity,resources.getString(R.string.clear_all)){
                    //清空所有追溯码
                    adapter.data.forEach {
                        it.drugTracInfoList?.clear()
                    }
                    adapter.notifyDataSetChanged()
                }
            }
            tvSave.clickN {
                var alert = false
                var noData = true
                adapter.data.forEach {
                    if (!it.drugTracInfoList.isNullOrEmpty()){
                        noData = false
                    }
                    var size = 0
                    it.drugTracInfoList?.forEach { drugInfo ->
                        if (drugInfo.drugTracCodeNum != null) {
                            size += drugInfo.drugTracCodeNum!!.toInt()
                        } else {
                            size++
                        }
                    }
                    var needCount = 0
                    needCount = try {
                        it.drugNum?.toDoubleOrNull()?.toInt() ?: 0
                    } catch (e: Exception) {
                        0
                    }
                    if (size < needCount) {
                        alert = true
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@PrescriptionDrugCollectionActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        BlueDialog(this@PrescriptionDrugCollectionActivity,resources.getString(R.string.scan_not_all)){
                            //保存数据
                            viewModel.finishScanDrugCode(FinishRequest("1",viewModel.prescriptioninfo.value,viewModel.Prescriptionbarcode))
                        }
                    }else{
                        //保存数据
                        viewModel.finishScanDrugCode(FinishRequest("1",viewModel.prescriptioninfo.value,viewModel.Prescriptionbarcode))
                    }
                }
            }
            recyclerView.adapter = adapter
        }
    }

    override fun initData() {
        viewModel.prescriptioninfo.postValue(mutableListOf())
    }

    override fun startObserve() {
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
            }
        })
        viewModel.prescriptioninfo.observe(this, Observer { list->
            if (!list.isNullOrEmpty()&& list.isNotEmpty()){
                val prescr = list[0]
                prescr.let {
                    it.dataForm = "02"
                    adapter.setCanScan(viewModel.canAdd)
                    if (viewModel.canAdd){
                        binding.llBottom.visibility = View.VISIBLE
                    }else{
                        binding.llBottom.visibility = View.GONE
                    }
                    if (it==null){
                        adapter.removeAllHeaderView()
                        adapter.setList(mutableListOf())
                    }else{
                        binding.prescriptiondrugcollectionalert.text =
                            resources.getString(R.string.please_scan2)
                        val view =  LayoutInflater.from(this).inflate(R.layout.layout_drup_collect_top_view,null)
                        val bind = DataBindingUtil.bind<LayoutDrupCollectTopViewBinding>(view)
                        bind?.apply {
                            tvDate.text = it.prescriptionTime
                            tvName.text = it.psnName
                        }
                        adapter.addHeaderView(view)
                        if (it.drugInfoList.isNullOrEmpty()){
                            adapter.setList(mutableListOf())
                            adapter.setEmptyView(R.layout.layout_nodata)
                        }else{
                            adapter.setList(it.drugInfoList)
                        }
                    }

                }
            }else{
                binding.llBottom.visibility = View.GONE
                adapter.removeAllHeaderView()
                adapter.setEmptyView(R.layout.layout_nodata)
                adapter.setList(mutableListOf())
                viewModel.selectIndex.value = -1
            }

        })
        viewModel.selectIndex.observe(this, Observer {
            var trugTracCodgIsGatherCount = 0
            adapter.data.forEachIndexed { index, drugInfoBean ->
                if (viewModel.barcode.isNotEmpty()) {
                    viewModel.trugTracCodgIsGatherData?.drugDictInfo?.forEach { temp ->
                        if (drugInfoBean.drugCode == temp.drugCode) {
                            if (drugInfoBean.drugTracInfoList != null && drugInfoBean.drugTracInfoList!!.size > 0) {
                                drugInfoBean.drugTracInfoList?.forEach { drug ->
                                    if (drug.drugTracCodg == viewModel.barcode) {
                                        if (drug.drugTracCodeNum != null) {
                                            trugTracCodgIsGatherCount += drug.drugTracCodeNum!!.toInt()
                                        } else {
                                            trugTracCodgIsGatherCount++
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
            adapter.data.forEachIndexed { index, drugInfoBean ->
                drugInfoBean.isSelected = it == index
                if (viewModel.barcode.isNotEmpty()) {
                    if (it == index ) {
                        var setAllCount = 0
//                        var setBarcodeCount = 0
                        drugInfoBean.drugTracInfoList?.forEach { drug ->
                            if (drug.drugTracCodeNum != null) {
                                setAllCount += drug.drugTracCodeNum!!.toInt()
//                                if (drug.drugTracCodg == viewModel.barcode) {
//                                    setBarcodeCount += drug.drugTracCodeNum!!.toInt()
//                                }
                            } else {
                                setAllCount++
//                                if (drug.drugTracCodg == viewModel.barcode) {
//                                    setBarcodeCount++
//                                }
                            }
                        }

                        // 解析药品总量
                        val maxNum = try {
                            drugInfoBean.drugNum!!.toDouble().toInt()
                        } catch (e: Exception) {
                            e.printStackTrace()
                            1
                        }
                        // 处理拆零系数 如果coff为空时的处理
                        var ipcoff = 0
                        ipcoff = try {
                            drugInfoBean.coff?.toInt() ?: 0
                        } catch (e: Exception) {
                            e.printStackTrace()
                            0
                        }
                        if (ipcoff > 0) {
                            if (ipcoff - viewModel.usedCount.toInt() - trugTracCodgIsGatherCount <= 0) {
                                BlueDialog(this, "该溯源码已绑定完毕，请更换溯源码", type = 1) {}
                                return@Observer
                            }
                        }
                        if (maxNum == setAllCount) {
                            drugInfoBean.trugTracCodgIsGatherCount=true
                            viewModel.trugTracCodgIsGather(viewModel.barcode)
                            Toast.makeText(this,"该药品溯源码添加超过上限", Toast.LENGTH_SHORT).show()
//                            BlueDialog(this, "该药品溯源码添加超过上限", type = 1) {}
                            return@Observer
                        }

                    }
                }
            }
            if (it!=-1){
                binding.recyclerView.scrollToPosition(it)
                adapter.data[it].isSelected = true
                if (viewModel.barcode.isNotEmpty()){
                    if(adapter.data[it].drugTracInfoList==null){
                        adapter.data[it].drugTracInfoList = mutableListOf()
                    }
                    var drugTracCodeNum = countDrugTracCodeNums(adapter.data[it])

                    adapter.data[it].drugTracInfoList!!.add(DrugTrace(drugTracCodg = viewModel.barcode,drugTracCodeNum = drugTracCodeNum))
                }
            }
            adapter.notifyDataSetChanged()
//            if (viewModel.lastIndex!=-1)
//            adapter.notifyItemChanged(viewModel.lastIndex)
        })

    }
    fun countDrugTracCodeNum(drugInfoBean: DrugInfoBean): Integer {
        if (drugInfoBean.trdnFlag != "1") return Integer(1)
        var maxNum = 1
        var scanNum = 0
        try {
            maxNum = drugInfoBean.drugNum!!.toDouble().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        drugInfoBean.drugTracInfoList?.forEach {
            try {
                scanNum += it.drugTracCodeNum!!.toInt()
            } catch (e: Exception) {
            }
        }
        var count = maxNum - scanNum
        if (count < 1) count = 1
        return Integer(count)
    }

    private fun countDrugTracCodeNums(drugInfoBean: DrugInfoBean): Integer {
        // 初始化一个变量来保存计算结果
        var count = 1
        if (drugInfoBean.trdnFlag != "1") {
            // 如果不是追踪药品，固定返回1
            return Integer(count)
        }
        // 解析药品总量
        val maxNum = try {
            drugInfoBean.drugNum!!.toDouble().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
            1
        }

        // 处理拆零系数 如果coff为空时的处理
        var ipcoff: Int? = try {
            drugInfoBean.coff?.toInt()?.coerceAtLeast(1)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
        var usedCount = 0
        if (!viewModel.usedCount.isNullOrEmpty()) {
            usedCount = viewModel.usedCount!!.toInt()
        }
        if (ipcoff != null) {
            ipcoff -= usedCount
        }


        // 计算已扫描总量
        var scanNum = 0
        drugInfoBean.drugTracInfoList?.forEach {
            try {
                scanNum += it.drugTracCodeNum!!.toInt()
            } catch (e: Exception) {
                // 忽略无效值
            }
        }

        // 计算剩余未扫描数量
        val remaining = maxNum - scanNum
        if (ipcoff == null) {
            //如果拆零系数为空
            count = if (scanNum == 0) {
                // 第一次扫码：返回全部数量
                maxNum
            } else {
                // 后续所有扫码：固定返回1
                1
            }
        } else if (maxNum <= ipcoff) {
            // 规则1: 如果药品总量小于等于拆零系数
            count = if (scanNum == 0) {
                // 第一次扫码：返回全部数量
                maxNum
            } else {
                // 后续扫码：固定返回1
                1
            }
        }
        // 规则2: 药品总量大于拆零系数
        else {
            count = when {
                // 如果剩余数量大于等于拆零系数，返回拆零系数
                remaining >= ipcoff -> ipcoff

                // 如果还有剩余（但不足一个整包装），返回剩余数量
                remaining > 0 -> remaining

                // 如果剩余为0或负数，返回1
                else -> 1
            }
        }

        // 在方法最后统一将count转换为Integer返回
        return Integer(count)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@PrescriptionDrugCollectionActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if (viewModel.prescriptioninfo.value.isNullOrEmpty()){
                            //无值扫的算处方码
                            viewModel.getPrescriptionInfo(barcodeMessage.barcode)
                        } else{
                            if(barcodeMessage.type== BarcodeType.SUYUAN){
                                if (viewModel.canAdd){
                                    //扫码去
                                    viewModel.trugTracCodgIsGather(barcodeMessage.barcode)
                                }
                            }else{
                                YellowDialog(this@PrescriptionDrugCollectionActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                            }

                        }
                    }
                }
            }
        }
    }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}